//
//  WuyouTangControlView.m
//  WuyouTang
//
//  Created by YB007 on 2019/11/7.
//  Copyright © 2019 cat. All rights reserved.
//

#import "WuyouTangControlView.h"

#import <ZFPlayer/UIView+ZFFrame.h>
#import <ZFPlayer/UIImageView+ZFCache.h>
#import <ZFPlayer/ZFUtilities.h>
#import "ZFLoadingView.h"
#import <ZFPlayer/ZFSliderView.h>
#import "UIImage+RKCircleImg.h"

#import "expensiveGiftV.h"
#import "continueGift.h"
#import "RKShowPaintedView.h"
#import "YBHomeRedObj.h"
@interface WuyouTangControlView()<haohuadelegate,ZFSliderViewDelegate>
{
    BOOL _muteChange;
    
    expensiveGiftV *haohualiwuV;//豪华礼物
    continueGift *continueGifts;//连送礼物
    UIView *liansongliwubottomview;
    
}
/// 封面图
@property (nonatomic, strong) UIImageView *coverImageView;
@property (nonatomic, strong) UIButton *playBtn;
@property (nonatomic, strong) ZFSliderView *sliderView;
@property (nonatomic, strong) UIImageView *bgImgView;
@property (nonatomic, strong) UIView *effectView;
@property(nonatomic,strong)RKShowPaintedView *paintedShowRegion;    //手绘礼物显示区域
@property(nonatomic,strong)UIButton *ttBackBtn;
@property(nonatomic,strong)UILabel *timeLb;

@end

@implementation WuyouTangControlView
@synthesize player = _player;

- (instancetype)init {
    self = [super init];
    if (self) {
        _muteChange = NO;
        [self addSubview:self.paintedShowRegion];
        liansongliwubottomview = [[UIView alloc]init];
        liansongliwubottomview.userInteractionEnabled = NO;
        liansongliwubottomview.backgroundColor = UIColor.clearColor;
        [self addSubview:liansongliwubottomview];
        liansongliwubottomview.frame = CGRectMake(0, statusbarHeight + 240,_window_width,140);

        [self addSubview:self.playBtn];
        [self addSubview:self.ttBackBtn];
        [_ttBackBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.mas_left).offset(statusbarHeight+10);
            make.top.equalTo(self.mas_top).offset(statusbarHeight+20);
            make.width.height.mas_equalTo(40);
        }];

        [self addSubview:self.sliderView];
        [self addSubview:self.timeLb];
        [self addSubview:self.zfVolumeView];
        [self resetControlView];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(volumeChanged:) name:@"AVSystemController_SystemVolumeDidChangeNotification" object:nil];
        
    }
    return self;
}
- (void)dealloc{
        [[NSNotificationCenter defaultCenter] removeObserver:self name:@"AVSystemController_SystemVolumeDidChangeNotification" object:nil];
}
/// 音量改变的通知
- (void)volumeChanged:(NSNotification *)notification {
    if (_muteChange == YES) {
        _muteChange = NO;
        return;
    }
    NSDictionary *userInfo = notification.userInfo;
    NSString *reasonstr = userInfo[@"AVSystemController_AudioVolumeChangeReasonNotificationParameter"];
    if ([reasonstr isEqualToString:@"ExplicitVolumeChange"]) {
        float volume = [ userInfo[@"AVSystemController_AudioVolumeNotificationParameter"] floatValue];
        self.currentVol = volume;
        [self.zfVolumeView updateProgress:volume withVolumeBrightnessType:ZFVolumeBrightnessTypeVolume];
    }
}
- (void)layoutSubviews {
    [super layoutSubviews];
    self.coverImageView.frame = self.player.currentPlayerManager.view.bounds;
    
    CGFloat min_x = 0;
    CGFloat min_y = 0;
    CGFloat min_w = 0;
    CGFloat min_h = 0;
    CGFloat min_view_w = self.zf_width;
    CGFloat min_view_h = self.zf_height;
    
    min_w = 100;
    min_h = 100;
    self.playBtn.frame = CGRectMake(min_x, min_y, min_w, min_h);
    self.playBtn.center = self.center;
    
    min_x = 0;
    min_y = min_view_h - 50 - ShowDiff-25;//80
    min_w = min_view_w;
    min_h = 20;
    self.sliderView.frame = CGRectMake(min_x, min_y-5, min_w, min_h);
    
    self.bgImgView.frame = self.bounds;
    self.effectView.frame = self.bgImgView.bounds;
    
    self.zfVolumeView.frame = self.sliderView.frame;
    NSLog(@"===%@",self.zfVolumeView);
    
    self.timeLb.frame = CGRectMake(0, self.sliderView.top-20, self.width, 20);
}

- (void)resetControlView {
    self.playBtn.hidden = YES;
    self.sliderView.value = 0;
    self.sliderView.bufferValue = 0;
    self.coverImageView.contentMode = UIViewContentModeScaleAspectFit;
    
    //礼物视图重置
    if (continueGifts) {
        [continueGifts stopTimerAndArray];
        [continueGifts initGift];
        [continueGifts removeFromSuperview];
        continueGifts = nil;
    }
    if (haohualiwuV) {
        [haohualiwuV stopHaoHUaLiwu];
        [haohualiwuV removeFromSuperview];
        haohualiwuV.expensiveGiftCount = nil;
        haohualiwuV = nil;
    }
    liansongliwubottomview.top = statusbarHeight+240;
    if (_paintedShowRegion) {
        [_paintedShowRegion destroyPaitend];
    }
}

/// 加载状态改变
- (void)videoPlayer:(ZFPlayerController *)videoPlayer loadStateChanged:(ZFPlayerLoadState)state {
    if (state == ZFPlayerLoadStatePrepare) {
        self.coverImageView.hidden = NO;
    } else if (state == ZFPlayerLoadStatePlaythroughOK || state == ZFPlayerLoadStatePlayable) {
        self.coverImageView.hidden = YES;
        self.effectView.hidden = NO;
        //缓冲的时候点击了暂停
        if (self.playBtn.hidden == NO) {
            [videoPlayer.currentPlayerManager pause];
        }
        // 青少年模式受限
        if ([YBYoungManager shareInstance].youngBan == 1) {
            self.playBtn.hidden = NO;
            [videoPlayer.currentPlayerManager pause];
        }
    }
    if ((state == ZFPlayerLoadStateStalled || state == ZFPlayerLoadStatePrepare) && videoPlayer.currentPlayerManager.isPlaying) {
        [self.sliderView startAnimating];
    } else {
        
        [self.sliderView stopAnimating];
    }
}
- (void)videoPlayer:(ZFPlayerController *)videoPlayer playStateChanged:(ZFPlayerPlaybackState)state {
//    NSLog(@"rk_===playState:%lu",(unsigned long)state);
    if (_isDisappear&&state==ZFPlayerPlayStatePlaying) {
        NSLog(@"rk_实行了");
        [self.player stopCurrentPlayingCell];
    }

}
/// 播放进度改变回调
- (void)videoPlayer:(ZFPlayerController *)videoPlayer currentTime:(NSTimeInterval)currentTime totalTime:(NSTimeInterval)totalTime {
//    NSLog(@"xxxxxx:%f",videoPlayer.bufferProgress);
    if (videoPlayer.bufferProgress >= 0.9) {
        [self.sliderView stopAnimating];
    }
    self.sliderView.value = videoPlayer.progress;
}

- (void)gestureSingleTapped:(ZFPlayerGestureControl *)gestureControl {
    
    if (self.ybContorEvent) {
        self.ybContorEvent(@"控制-单击",gestureControl);
    }
}
#pragma mark - sss
- (void)gestureDoubleTapped:(ZFPlayerGestureControl *)gestureControl {
    if (self.ybContorEvent) {
        self.ybContorEvent(@"控制-双击",gestureControl);
    }
}

- (void)gestureEndedPan:(ZFPlayerGestureControl *)gestureControl panDirection:(ZFPanDirection)direction panLocation:(ZFPanLocation)location;{
    if (direction == 2 && location == 2) {
        //侧滑进入个人主页
        if (self.ybContorEvent) {
            self.ybContorEvent(@"控制-主页",gestureControl);
        }
        NSLog(@"rk======>向右滑动");
    }else if (direction == 2 && location == 1){
        NSLog(@"rk======>向左滑动");
        if (self.ybContorEvent) {
            self.ybContorEvent(@"控制-观看左滑",gestureControl);
        }
    }
    NSLog(@"rk======>end--dir:%lu==loc:%lu",(unsigned long)direction,(unsigned long)location);
}
#pragma mark - eeee

-(void)controlSingleTapped {
    if (self.player.currentPlayerManager.isPlaying) {
        [[YBHomeRedObj redInstance]timerPause];

        [self.player.currentPlayerManager pause];
        NSLog(@"22222===:%lu",self.player.currentPlayerManager.playState);
        self.playBtn.hidden = NO;
        self.playBtn.transform = CGAffineTransformMakeScale(1.5f, 1.5f);
        [UIView animateWithDuration:0.2f delay:0
                            options:UIViewAnimationOptionCurveEaseIn animations:^{
            self.playBtn.transform = CGAffineTransformIdentity;
        } completion:^(BOOL finished) {
        }];
    } else {
        [self.player.currentPlayerManager play];
        self.playBtn.hidden = YES;
        [[NSNotificationCenter defaultCenter]postNotificationName:@"lookCountGo" object:nil];

    }
}
-(void)videoMuted:(BOOL)mute{
    _muteChange = YES;
    [self.player setMuted:mute];
}
-(void)showPlayBtn{
    self.playBtn.hidden = NO;
    if (self.player.currentPlayerManager.isPlaying) {
        [self.player.currentPlayerManager pause];
    }
}
-(void)hiddenPlayBtn {
    [self.player.currentPlayerManager play];
    self.playBtn.hidden = YES;
}
- (void)setPlayer:(ZFPlayerController *)player {
    _player = player;
    [player.currentPlayerManager.view insertSubview:self.bgImgView atIndex:0];
    /*
    [self.bgImgView addSubview:self.effectView];
     */
    [player.currentPlayerManager.view insertSubview:self.coverImageView atIndex:1];
}

- (void)showCoverViewWithUrl:(NSString *)coverUrl withImageMode:(UIViewContentMode)contentMode {
    self.coverImageView.contentMode = contentMode;
    [self.coverImageView sd_setImageWithURL:[NSURL URLWithString:coverUrl] placeholderImage:[UIImage imageNamed:@"img_video_loading"]];
    /*
    [self.bgImgView sd_setImageWithURL:[NSURL URLWithString:coverUrl] placeholderImage:[UIImage imageNamed:@"loading_bgView"]];
     */
}

#pragma mark - 打赏开始
-(void)showGift:(NSDictionary *)playDic {
    NSString *type = minstr([playDic valueForKey:@"type"]);
    if (!continueGifts) {
        continueGifts = [[continueGift alloc]initWithFrame:CGRectMake(0, 0, liansongliwubottomview.width, liansongliwubottomview.height)];
        [liansongliwubottomview addSubview:continueGifts];
        //初始化礼物空位
        [continueGifts initGift];
        YBWeakSelf;
        continueGifts.rkPaintedEvent = ^(NSDictionary *giftDic) {
            [weakSelf showPaintedGift:giftDic];
        };
    }
    if ([type isEqual:@"1"]) {
        [self expensiveGift:playDic];
    }else{
        //手绘以及普通礼物都进 continueGifts 由它执行队列
        [continueGifts GiftPopView:playDic andLianSong:@"Y"];
    }
}
-(void)showPaintedGift:(NSDictionary *)giftDic {
    //手绘显示动画
    _paintedShowRegion.giftPathStr = minstr([giftDic valueForKey:@"gifticon"]);
    _paintedShowRegion.paintedWidth = [minstr([giftDic valueForKey:@"paintedWidth"]) floatValue];
    _paintedShowRegion.paintedHeight = [minstr([giftDic valueForKey:@"paintedHeight"]) floatValue];
    _paintedShowRegion.paintedPointArray = [NSArray arrayWithArray:[giftDic valueForKey:@"paintedPath"]];
}
/************ 礼物弹出及队列显示开始 *************/
-(void)expensiveGiftdelegate:(NSDictionary *)giftData{
    if (!haohualiwuV) {
        haohualiwuV = [[expensiveGiftV alloc]init];
        haohualiwuV.delegate = self;
        [self addSubview:haohualiwuV];
    }
    if (giftData == nil) {
        
    }else {
        [haohualiwuV addArrayCount:giftData];
    }
    if(haohualiwuV.haohuaCount == 0){
        [haohualiwuV enGiftEspensive];
    }
}
-(void)expensiveGift:(NSDictionary *)giftData{
    if (!haohualiwuV) {
        haohualiwuV = [[expensiveGiftV alloc]init];
        haohualiwuV.delegate = self;
        [self addSubview:haohualiwuV];
    }
    if (giftData == nil) {
     
    }else {
        [haohualiwuV addArrayCount:giftData];
    }
    if(haohualiwuV.haohuaCount == 0){
        [haohualiwuV enGiftEspensive];
    }
}
#pragma mark - 打赏结束

#pragma mark - getter

- (UIImageView *)bgImgView {
    if (!_bgImgView) {
        _bgImgView = [[UIImageView alloc] init];
        _bgImgView.userInteractionEnabled = YES;
        //[_bgImgView setImage:[UIImage imageNamed:@"img_video_loading"]];
        [_bgImgView setImage:[PublicObj getImgWithColor:CellRow_Cor]];
    }
    return _bgImgView;
}

- (UIView *)effectView {
    if (!_effectView) {
        if (@available(iOS 8.0, *)) {
            UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
            _effectView = [[UIVisualEffectView alloc] initWithEffect:effect];
        } else {
            UIToolbar *effectView = [[UIToolbar alloc] init];
            effectView.barStyle = UIBarStyleBlackTranslucent;
            _effectView = effectView;
        }
    }
    return _effectView;
}
- (ZFVolumeBrightnessView *)zfVolumeView {
    if (!_zfVolumeView) {
        _zfVolumeView = [[ZFVolumeBrightnessView alloc]init];
        _zfVolumeView.backgroundColor = RGB_COLOR(@"#000000", 0.2);
    }
    return _zfVolumeView;
}

- (UIButton *)playBtn {
    if (!_playBtn) {
        _playBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _playBtn.userInteractionEnabled = NO;
        [_playBtn setImage:[UIImage imageNamed:@"icon_play_pause"] forState:UIControlStateNormal];
    }
    return _playBtn;
}
#pragma mark - 全屏返回按钮
- (UIButton *)ttBackBtn {
    if (!_ttBackBtn) {
        _ttBackBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_ttBackBtn setImage:[UIImage imageNamed:@"video_返回"] forState:0];
        [_ttBackBtn addTarget:self action:@selector(clickTtBackBtn) forControlEvents:UIControlEventTouchUpInside];
        _ttBackBtn.hidden = YES;
        _ttBackBtn.jk_touchAreaInsets = UIEdgeInsetsMake(20, 20, 20, 20);
    }
    return _ttBackBtn;
}
-(void)clickTtBackBtn {
    BOOL cuurentIsFull = [self.player isFullScreen];
    [self.player enterFullScreen:!cuurentIsFull animated:YES];
}

-(void)changeFullScreen:(BOOL)isFull;{
    _ttBackBtn.hidden = !isFull;
}

- (ZFSliderView *)sliderView {
    if (!_sliderView) {
        _sliderView = [[ZFSliderView alloc] init];
        _sliderView.delegate = self;
        _sliderView.maximumTrackTintColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.2];
        _sliderView.minimumTrackTintColor = [UIColor whiteColor];
        _sliderView.bufferTrackTintColor  = [UIColor clearColor];
        _sliderView.sliderHeight = 1;
        _sliderView.isHideSliderBlock = NO;
        _sliderView.sliderHeight = 2;
        _sliderView.isHideSliderBlock = NO;
        UIImage *pointImg = [PublicObj getImgWithColor:RGB_COLOR(@"#ffffff", 1)withSize:CGSizeMake(10, 10)];
        [_sliderView setThumbImage:[pointImg rk_circleImage] forState:0];

//        _sliderView.backgroundColor = UIColor.redColor;
    }
    return _sliderView;
}
-(UILabel *)timeLb{
    if(!_timeLb){
        _timeLb = [[UILabel alloc]init];
        _timeLb.textColor = UIColor.whiteColor;
        _timeLb.textAlignment = NSTextAlignmentCenter;
        _timeLb.font = [UIFont systemFontOfSize:14];
        _timeLb.hidden = YES;
    }
    return _timeLb;
}
- (UIImageView *)coverImageView {
    if (!_coverImageView) {
        _coverImageView = [[UIImageView alloc] init];
        _coverImageView.userInteractionEnabled = YES;
        _coverImageView.clipsToBounds = YES;
    }
    return _coverImageView;
}
- (RKShowPaintedView *)paintedShowRegion {
    if (!_paintedShowRegion) {
        _paintedShowRegion = [[RKShowPaintedView alloc]init];
        //_paintedShowRegion.backgroundColor = UIColor.redColor;
    }
    return _paintedShowRegion;
}
#pragma mark - ZFSliderViewDelegate
- (void)sliderTouchBegan:(float)value {
    self.sliderView.isdragging = YES;
    self.timeLb.hidden = NO;
}

- (void)sliderTouchEnded:(float)value {
    if (self.player.totalTime > 0) {
        @zf_weakify(self)
        
        NSTimeInterval currentTime = self.player.totalTime*value;
        
        
//        NSLog(@"sliderTouchEnded=====current:%@",currentTime);
//        /// 判断是否大于免费时长
//        CGFloat freeTime = [minstr([_curVideoDic valueForKey:@"minute"]) floatValue] * 60;
//
//        /// 提示判断
//        BOOL clickCon = [TTCatchInfo getClickContinue];
//        int issubscribe = [minstr([_curVideoDic valueForKey:@"issubscribe"]) intValue];
//
//        if (issubscribe == 0 && clickCon == NO && currentTime > freeTime) {
//            currentTime = freeTime;
//            [self pauseVideo];
//            [self freeTimeEnd];
//            self.sliderView.value = currentTime/self.player.totalTime;
//            self.sliderView.isdragging = NO;
//        }
//        NSString *videoId = minstr([_curVideoDic valueForKey:@"id"]);
//        CGFloat videoOldVal = [TTCatchInfo getVideoMaxTimewithVideoid:videoId];
//        //NSLog(@"rk_tt-拖动结束旧的观看时长:%f",videoOldVal);
//        if (currentTime > videoOldVal) {
//            [TTCatchInfo saveVideoMaxTime:currentTime withVideoid:videoId];
            //NSLog(@"rk_tt-拖动结束save==>new:%f",[TTCatchInfo getVideoMaxTimewithVideoid:videoId]);
//        }
        
        [self.player seekToTime:currentTime completionHandler:^(BOOL finished) {
            @zf_strongify(self)
            if (finished) {
                self.sliderView.isdragging = NO;
                self.timeLb.hidden = YES;
            }
        }];
    } else {
        self.sliderView.isdragging = NO;
    }
}

- (void)sliderValueChanged:(float)value {
    if (self.player.totalTime == 0) {
        self.sliderView.value = 0;
        return;
    }
    self.sliderView.isdragging = YES;
    NSString *currentTimeString = [ZFUtilities convertTimeSecond:self.player.totalTime*value];
    NSString *allTimeString = [ZFUtilities convertTimeSecond:self.player.totalTime];

    NSLog(@"sliderTouchEnded=====currentTimeString:%@\nall:%@",currentTimeString,allTimeString);
    self.timeLb.text = [NSString stringWithFormat:@"%@/%@",currentTimeString,allTimeString];
}

- (void)sliderTapped:(float)value {
    if (self.player.totalTime > 0) {
        self.sliderView.isdragging = YES;
        
        NSTimeInterval currentTime = self.player.totalTime*value;
        

//        /// 判断是否大于免费时长
//        CGFloat freeTime = [minstr([_curVideoDic valueForKey:@"minute"]) floatValue] * 60;
//
//        /// 提示判断
//        BOOL clickCon = [TTCatchInfo getClickContinue];
//        int issubscribe = [minstr([_curVideoDic valueForKey:@"issubscribe"]) intValue];
//
//        if (issubscribe == 0 && clickCon == NO && currentTime > freeTime) {
//            currentTime = freeTime;
//            [self pauseVideo];
//            [self freeTimeEnd];
//            self.sliderView.value = currentTime/self.player.totalTime;
//            self.sliderView.isdragging = NO;
//        }
//        NSString *videoId = minstr([_curVideoDic valueForKey:@"id"]);
//        CGFloat videoOldVal = [TTCatchInfo getVideoMaxTimewithVideoid:videoId];
//        //NSLog(@"rk_tt-拖动结束旧的观看时长:%f",videoOldVal);
//        if (currentTime > videoOldVal) {
//            [TTCatchInfo saveVideoMaxTime:currentTime withVideoid:videoId];
//            //NSLog(@"rk_tt-拖动结束save==>new:%f",[TTCatchInfo getVideoMaxTimewithVideoid:videoId]);
//        }
        @zf_weakify(self)
        [self.player seekToTime:currentTime completionHandler:^(BOOL finished) {
            @zf_strongify(self)
            if (finished) {
                self.sliderView.isdragging = NO;
                //[self.player.currentPlayerManager play];
            }
        }];
    } else {
        self.sliderView.isdragging = NO;
        self.sliderView.value = 0;
    }
}

@end
